package controller;

import domain.Permission;
import domain.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import service.IPermissionService;
import service.IRoleService;

import javax.annotation.security.RolesAllowed;
import java.util.Arrays;
import java.util.List;

/**
 * @author Freedy
 * @date 2020/12/25 23:18
 */
@Controller
@RequestMapping("/role")
@RolesAllowed({"ADMIN"})
public class RoleController {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/findAll.do")
    public ModelAndView findAll() throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        List<Role> roles = roleService.findAll();
        modelAndView.addObject("roleList",roles);
        modelAndView.setViewName("role-list");
        return modelAndView;
    }

    @RequestMapping("/save.do")
    public String save(Role role) throws Exception{
        roleService.save(role);
        return "redirect:findAll.do";
    }

    @RequestMapping("/findById.do")
    public ModelAndView findById(String id) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        Role role=roleService.findById(id);
        modelAndView.addObject("role",role);
        modelAndView.setViewName("role-show-one");
        return modelAndView;
    }

    @RequestMapping("/listPermissionById.do")
    public ModelAndView listPermissionById(String id) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        List<Permission> list = permissionService.findAllWithOutItself(id);
        modelAndView.addObject("permissionList",list);
        modelAndView.addObject("id",id);
        modelAndView.setViewName("add-permission-list");
        return modelAndView;
    }

    @RequestMapping("/addPermission.do")
    public String addPermission(Integer[] ids,Integer id) throws Exception {
        roleService.addPermissionByRoleId(ids,id);
        return "redirect:findAll.do";
    }

    @RequestMapping("/deleteRole.do")
    public String deleteRole(String id) throws Exception {
        roleService.deleteRole(id);
        return "redirect:findAll.do";
    }

}
